﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace Forum.Filter
{
    // 声明特性，并指定标记位置为方法
    [AttributeUsage(AttributeTargets.Method)]
    public class PreventDuplicateRequestsAttribute : Attribute, IFilterFactory
    {
        private readonly int _expiredSeconds;//用于记录缓存的过期时间
        private readonly string[] _factorNames;//用于记录幂等性校验的因素名

        public PreventDuplicateRequestsAttribute(int expiredMinutes, params string[] factorNames)
        {
            _expiredSeconds = expiredMinutes;
            _factorNames = factorNames;
        }

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            // 通过依赖注入获取 PreventDuplicateRequestsActionFilter 过滤器实例
            var filter = serviceProvider.GetService<PreventDuplicateRequestsActionFilter>();
            if (filter == null) throw new InvalidOperationException();
            filter.FactorNames = _factorNames;
            filter.Seconds = _expiredSeconds;
            return filter;
        }
        // 实现 IFilterFactory 接口中的 IsReusable 方法，指示过滤器实例是否可重用
        public bool IsReusable => false;
    }
}
